package controllers

import (
	"ErgoGo/internal/model/conf"

	"github.com/gin-gonic/gin"
)

// SettingsForm 显示设置页面
func SettingsForm(c *gin.Context) {
	// 获取当前设置
	prefix := conf.GetConfig(conf.Prefix)
	articleLength := conf.GetConfig(conf.ArticleLength)
	categories := conf.GetCategories()
	defaultCategory := conf.GetDefaultCategory()

	// 如果文章长度设置为空，设置默认值
	if articleLength == "" {
		articleLength = "medium"
	}

	c.HTML(200, "settings", gin.H{
		"title":          "系统设置",
		"showHeader":     true,
		"active":         "settings",
		"prefix":         prefix,
		"articleLength":  articleLength,
		"categories":     categories,
		"defaultCategory": defaultCategory,
	})
}

// SettingsSave 保存设置
func SettingsSave(c *gin.Context) {
	prefix := c.PostForm("prefix")
	articleLength := c.PostForm("article_length")
	categoryIds := c.PostFormArray("category_ids[]")
	categoryNames := c.PostFormArray("category_names[]")
	defaultCategory := c.PostForm("default_category")

	// 保存设置
	conf.SetConfig(conf.Prefix, prefix)
	conf.SetConfig(conf.ArticleLength, articleLength)
	conf.SetDefaultCategory(defaultCategory)

	// 保存栏目设置
	var categories []conf.Category
	for i := 0; i < len(categoryIds); i++ {
		if categoryIds[i] != "" && categoryNames[i] != "" {
			categories = append(categories, conf.Category{
				ID:   categoryIds[i],
				Name: categoryNames[i],
			})
		}
	}
	conf.SetCategories(categories)

	c.HTML(200, "settings", gin.H{
		"title":          "系统设置",
		"showHeader":     true,
		"active":         "settings",
		"prefix":         prefix,
		"articleLength":  articleLength,
		"categories":     categories,
		"defaultCategory": defaultCategory,
		"Success":        true,
	})
}
